package userFileModuleApi

import (
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/enums"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/model"
	"KumquatDrivesServices/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"path/filepath"
)

type reNameRequest struct {
	FileName string                `json:"newFileName" binding:"required"`
	FileId   model.SnowflakeIdType `json:"fileId" binding:"required"`
}

func (UserFileModuleApi) ReName(c *gin.Context) {
	var req reNameRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		logrus.Errorf("ShouldBindJSON error:%v", err)
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	userId := utils.GetUserId(c)
	if userId == 0 {
		logrus.Errorf("GetUserId  error:%v", fmt.Errorf("login expired"))
		res.FailWithCode(res.LOGIN_EXPIRED, c)
		return
	}
	//检查文件是否存在
	var fileModel model.FileModel
	if err := global.DB.Where("id=? and user_id=?", req.FileId, userId).First(&fileModel).Error; err != nil {
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	//检查同级目录下是否有同名文件
	newFileName := utils.GetBaseNameWithoutExt(req.FileName) + filepath.Ext(fileModel.FilePath)
	if req.FileName == newFileName {
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	bol, err := utils.CheckSameNameFileOrDir(fileModel.FilePid, userId, newFileName, fileModel.IsFolder)
	if err != nil {
		logrus.Errorf("CheckSameNameFileOrDir error:%v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	if bol {
		switch fileModel.IsFolder {
		case enums.Folder:
			res.FailWithCode(res.SAME_FOLDER_NAME_EXISTS, c)
		default:
			res.FailWithCode(res.SAME_FILE_EXISTS, c)
		}
		return
	}
	//更新文件名
	tx := global.DB.Begin()
	query := tx.Model(model.FileModel{}).Where("file_pid=? and user_id=? and id=? and is_folder=? and del_flag=?",
		fileModel.FilePid, userId, req.FileId, fileModel.IsFolder, enums.Normal)
	if err = query.Update("file_name", newFileName).Error; err != nil {
		tx.Rollback()
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	if err = tx.Commit().Error; err != nil {
		tx.Rollback()
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	res.OkWithData(res.EmptyData, c)
}
